package com.sanji.sjmallwidget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;

import com.sanji.sjmallapp.R;

/**
 * Created by zsf on 17-1-10.
 */

public class BottomPopWindow extends PopupWindow {

    private View bottomView;
    private Context mContext;

    private WindowManager.LayoutParams mParams;


    public BottomPopWindow(Context context,View layout){
        super(layout, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        this.mContext = context;
        initWindow(layout);

        mParams = ((Activity)context).getWindow().getAttributes();
    }

    //更改背景透明度
    public void setBgAlpha(float alpha){
        if (mParams != null){
            mParams.alpha = alpha;
            ((Activity)mContext).getWindow().setAttributes(mParams);
        }
    }

    public void initWindow(View view){
        //设置弹出窗体可点击
        setFocusable(true);
        setFocusable(true);
        //实例化一个 colorDrawable颜色半透明
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        setBackgroundDrawable(dw);
        setAnimationStyle(R.style.my_popwindow);

        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int height = view.getTop();
                int y = (int) motionEvent.getY();
                if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                    if (y < height){
                        dismiss();
                    }
                }
                return true;
            }
        });
    }

    public void show(View parent){
        if (((Activity)mContext).getCurrentFocus() != null){
            ((InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(((Activity)mContext).getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

        }

        setBgAlpha(0.4f);

        showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,0);
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
    }

    @Override
    public void dismiss() {
        setBgAlpha(1f);
        super.dismiss();
    }
}
